//
//  HJJsonAnimationView.m
//  KaiChat
//
//  Created by lx on 2023/11/1.
//

#import "HJJsonAnimationView.h"
#import "KaiChat-Swift.h"


@interface HJJsonAnimationView()

@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) JsonAnimationView *animationView;

@end


@implementation HJJsonAnimationView

- (HJJsonAnimationView *)initWithName:(NSString *)name {
    if (self = [super init]) {
        self.name = name;
        [self addSubview:self.animationView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _animationView.frame = self.bounds;
}


- (JsonAnimationView *)animationView {
    if (!_animationView) {
        _animationView = [[JsonAnimationView alloc] initWithName:self.name];
    }
    return _animationView;
}
 

- (void)playComplete:(void (^)(BOOL))complete {
    if (!_animationView) {
        [self addSubview:self.animationView];
    }
    
    _imageView.hidden = YES;
    
    TJWeakify(self)
    [_animationView playWithComplete:^(BOOL res) {
        if (res) {
            if (weakself.isLastFrame) {
                
                UIImage *image = [HJTools convertViewToImage:weakself.animationView];
                weakself.imageView = [UIImageView addToView:weakself];
                weakself.imageView.frame = weakself.bounds;
                weakself.imageView.image = image;
                weakself.imageView.hidden = NO;

                [weakself.animationView removeFromSuperview];
                weakself.animationView = nil;
            }
        }
        
        if (complete) {
            complete(res);
        }
    }];
}

- (void)pause {
    [_animationView pause];
}

- (void)stop {
    [_animationView stop];
}

@end
